#!/usr/bin/env node

/**
 * 真正的Excel导入测试
 * 创建真实的Excel文件并通过UI上传测试
 */

const XLSX = require('xlsx');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

class RealExcelImportTest {
  constructor() {
    this.baseDir = '/Users/andylau/Dropbox/AppDevelopment/CMB250716';
    this.testTimestamp = Date.now().toString();
  }

  log(message, type = 'info') {
    const timestamp = new Date().toISOString();
    const prefix = {
      'info': '🔍',
      'success': '✅',
      'error': '❌',
      'warning': '⚠️'
    }[type] || 'ℹ️';
    console.log(`${prefix} [${timestamp}] ${message}`);
  }

  createRealExcelFile() {
    this.log('创建真实的Excel测试文件');
    
    const workbook = XLSX.utils.book_new();
    
    // Dishes工作表 - 严格按照V2 schema
    const dishesData = [
      // 表头
      ['dish_sku', 'dish_slug', 'name_zh', 'name_en', 'category', 'base_status', 'description_zh', 'description_en', 'ingredients_zh', 'ingredients_en', 'tags', 'popularity'],
      // 数据行
      [`REAL_TEST_${this.testTimestamp}_001`, `real-test-burger-${this.testTimestamp}`, `真实测试汉堡_${this.testTimestamp}`, `Real Test Burger ${this.testTimestamp}`, '主食', 'active', '这是真实的Excel导入测试汉堡', 'This is a real Excel import test burger', '牛肉,生菜,面包', 'Beef, Lettuce, Bread', '测试,真实导入', '85'],
      [`REAL_TEST_${this.testTimestamp}_002`, `real-test-drink-${this.testTimestamp}`, `真实测试饮料_${this.testTimestamp}`, `Real Test Drink ${this.testTimestamp}`, '饮品', 'active', '这是真实的Excel导入测试饮料', 'This is a real Excel import test drink', '水,糖,柠檬', 'Water, Sugar, Lemon', '测试,清爽', '75'],
      [`REAL_TEST_${this.testTimestamp}_003`, `real-test-dessert-${this.testTimestamp}`, `真实测试甜品_${this.testTimestamp}`, `Real Test Dessert ${this.testTimestamp}`, '甜品', 'active', '这是真实的Excel导入测试甜品', 'This is a real Excel import test dessert', '面粉,糖,奶油', 'Flour, Sugar, Cream', '测试,甜蜜', '90']
    ];
    
    const dishesWS = XLSX.utils.aoa_to_sheet(dishesData);
    XLSX.utils.book_append_sheet(workbook, dishesWS, 'Dishes');
    
    // Variants工作表
    const variantsData = [
      // 表头
      ['dish_sku', 'name_zh', 'variant_code', 'variant_name', 'price', 'compare_at_price', 'is_default', 'stock'],
      // 数据行
      [`REAL_TEST_${this.testTimestamp}_001`, '标准', 'STD-001', 'Standard', '25.99', '', 'true', '100'],
      [`REAL_TEST_${this.testTimestamp}_001`, '大份', 'LRG-001', 'Large', '29.99', '32.99', 'false', '80'],
      [`REAL_TEST_${this.testTimestamp}_002`, '中杯', 'MED-001', 'Medium', '12.99', '', 'true', '150'],
      [`REAL_TEST_${this.testTimestamp}_002`, '大杯', 'LRG-002', 'Large', '15.99', '18.99', 'false', '120'],
      [`REAL_TEST_${this.testTimestamp}_003`, '标准', 'STD-003', 'Standard', '18.99', '', 'true', '60']
    ];
    
    const variantsWS = XLSX.utils.aoa_to_sheet(variantsData);
    XLSX.utils.book_append_sheet(workbook, variantsWS, 'Variants');
    
    // Options工作表
    const optionsData = [
      // 表头
      ['dish_sku', 'name_zh', 'group_code', 'group_name', 'required', 'value_code', 'value_name', 'price_delta'],
      // 数据行
      [`REAL_TEST_${this.testTimestamp}_001`, '配菜选择', 'SIDE', '配菜', 'false', 'FRIES', '薯条', '3.00'],
      [`REAL_TEST_${this.testTimestamp}_001`, '配菜选择', 'SIDE', '配菜', 'false', 'SALAD', '沙拉', '5.00'],
      [`REAL_TEST_${this.testTimestamp}_002`, '温度选择', 'TEMP', '温度', 'true', 'ICE', '冰', '0'],
      [`REAL_TEST_${this.testTimestamp}_002`, '温度选择', 'TEMP', '温度', 'true', 'HOT', '热', '0'],
      [`REAL_TEST_${this.testTimestamp}_003`, '装饰选择', 'DECO', '装饰', 'false', 'CHERRY', '樱桃', '2.00']
    ];
    
    const optionsWS = XLSX.utils.aoa_to_sheet(optionsData);
    XLSX.utils.book_append_sheet(workbook, optionsWS, 'Options');
    
    // 保存文件
    const fileName = `real_excel_import_test_${this.testTimestamp}.xlsx`;
    const filePath = path.join(this.baseDir, fileName);
    
    XLSX.writeFile(workbook, filePath);
    
    this.log(`Excel文件已创建: ${fileName}`, 'success');
    this.log(`文件路径: ${filePath}`);
    
    return { fileName, filePath };
  }

  async runUITest(filePath) {
    this.log('开始UI自动化测试');
    
    try {
      // 创建Playwright测试脚本
      const testScript = `
const { test, expect } = require('@playwright/test');

test('真实Excel导入UI测试', async ({ page }) => {
  // 设置超时
  test.setTimeout(300000);
  
  console.log('开始真实Excel导入UI测试');
  
  // 访问管理后台
  await page.goto('http://localhost:5174/menu');
  
  // 等待页面加载
  await page.waitForTimeout(3000);
  
  // 检查是否需要登录
  const loginBtn = page.locator('button:has-text("登录")');
  if (await loginBtn.isVisible({ timeout: 2000 })) {
    console.log('需要登录，使用调试token');
    await page.evaluate(() => {
      localStorage.setItem('admin_token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJtZW1iZXJzaGlwTGV2ZWwiOiJhZG1pbiIsImlhdCI6MTc1NzE2NDAyMCwiZXhwIjoxNzU3NzY4ODIwLCJpc3MiOiJjdS1tci1idWxsLWFwaSJ9.2pqn01o6rqlOOoOGaEPXNtwIoK-A86kPty3KWnyvY0Q');
    });
    await page.reload();
    await page.waitForTimeout(3000);
  }
  
  console.log('查找导入按钮');
  
  // 查找导入按钮
  const importBtn = page.locator('button:has-text("导入")');
  await importBtn.first().waitFor({ timeout: 10000 });
  
  console.log('点击导入按钮');
  await importBtn.first().click();
  
  // 等待文件输入框出现
  await page.waitForTimeout(2000);
  
  console.log('查找文件输入框');
  const fileInput = page.locator('input[type="file"]');
  await fileInput.waitFor({ timeout: 10000 });
  
  console.log('上传Excel文件: ${filePath}');
  await fileInput.setInputFiles('${filePath}');
  
  // 等待上传和处理
  console.log('等待文件处理...');
  await page.waitForTimeout(10000);
  
  // 检查是否有成功消息或错误消息
  const successMsg = page.locator('.ant-message-success, .ant-notification-notice-success');
  const errorMsg = page.locator('.ant-message-error, .ant-notification-notice-error');
  
  if (await successMsg.isVisible({ timeout: 5000 })) {
    console.log('✅ 导入成功消息出现');
  } else if (await errorMsg.isVisible({ timeout: 5000 })) {
    const errorText = await errorMsg.textContent();
    console.log('❌ 导入失败: ' + errorText);
    throw new Error('导入失败: ' + errorText);
  } else {
    console.log('⚠️ 未检测到明确的成功或失败消息');
  }
  
  // 等待页面刷新或数据更新
  await page.waitForTimeout(5000);
  
  // 检查表格中是否出现了新数据
  console.log('检查表格数据...');
  const tableRows = page.locator('table tbody tr');
  const rowCount = await tableRows.count();
  console.log('表格行数: ' + rowCount);
  
  // 查找包含测试数据的行
  const testDataRow = page.locator('td:has-text("真实测试汉堡_${this.testTimestamp}")');
  if (await testDataRow.isVisible({ timeout: 5000 })) {
    console.log('✅ 找到导入的测试数据！');
  } else {
    console.log('❌ 未找到导入的测试数据');
    // 打印当前表格内容用于调试
    const tableText = await page.locator('table').textContent();
    console.log('当前表格内容:', tableText.substring(0, 500));
    throw new Error('未找到导入的测试数据');
  }
  
  console.log('✅ 真实Excel导入UI测试完成！');
});
`;
      
      // 写入测试文件
      const testFilePath = path.join(this.baseDir, 'admin-tests/tests/real-excel-import-ui.spec.js');
      fs.writeFileSync(testFilePath, testScript);
      
      this.log('Playwright测试脚本已创建');
      
      // 运行测试
      this.log('运行Playwright UI测试...');
      const result = execSync(
        `cd ${this.baseDir}/admin-tests && npx playwright test tests/real-excel-import-ui.spec.js --reporter=line`,
        { encoding: 'utf8', timeout: 300000 }
      );
      
      this.log('UI测试完成', 'success');
      console.log(result);
      
      return true;
    } catch (error) {
      this.log(`UI测试失败: ${error.message}`, 'error');
      console.log(error.stdout || error.stderr || error.message);
      return false;
    }
  }

  async run() {
    console.log('\n' + '='.repeat(60));
    console.log('🎯 真实Excel导入功能测试');
    console.log('='.repeat(60) + '\n');
    
    try {
      // 1. 创建真实的Excel文件
      const { fileName, filePath } = this.createRealExcelFile();
      
      // 2. 运行UI测试
      const success = await this.runUITest(filePath);
      
      console.log('\n' + '='.repeat(60));
      if (success) {
        console.log('✅ 真实Excel导入测试成功！');
        console.log('🎉 Excel文件中的数据已正确导入并显示在UI中！');
      } else {
        console.log('❌ 真实Excel导入测试失败！');
        console.log('💡 请检查UI界面和导入流程');
      }
      console.log('='.repeat(60) + '\n');
      
    } catch (error) {
      this.log(`测试异常: ${error.message}`, 'error');
      console.log('❌ 真实Excel导入测试异常');
    }
  }
}

// 立即运行
if (require.main === module) {
  const test = new RealExcelImportTest();
  test.run().catch(console.error);
}

module.exports = RealExcelImportTest;